package com.example.chatroom.service.impl;

import com.example.chatroom.domain.ChatHistory;
import com.example.chatroom.dto.HistoryMessageDTO;
import com.example.chatroom.repository.ChatHistoryRepository;
import com.example.chatroom.service.ChatService;
import com.example.chatroom.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class ChatServiceImpl implements ChatService {

    private ChatHistoryRepository chatHistoryRepository;

    private UserInfoService userInfoService;

    @Autowired
    public ChatServiceImpl(ChatHistoryRepository chatHistoryRepository, UserInfoService userInfoService) {
        this.chatHistoryRepository = chatHistoryRepository;
        this.userInfoService = userInfoService;
    }


    @Override
    public void saveHistoryMessage(Map<String, Object> map, Long fromUserId, Long toUserId) {
        ChatHistory chatHistory = new ChatHistory();
        String message = map.get("message").toString();
        Timestamp date = Timestamp.valueOf(map.get("date").toString());
        String emotion = map.get("emotion").toString();
        chatHistory.setFromUserId(fromUserId);
        chatHistory.setToUserId(toUserId);
        chatHistory.setContent(message);
        chatHistory.setEmotion(emotion);
        chatHistory.setDate(date);
        chatHistoryRepository.save(chatHistory);
    }

    @Override
    public List<HistoryMessageDTO> findHistory(Long toUserId, HttpServletRequest request) {
        List<ChatHistory> chatHistoryList = chatHistoryRepository.getHistory(toUserId);
        List<HistoryMessageDTO> historyMessageDTOList = new ArrayList<>();
        for (ChatHistory chatHistory : chatHistoryList) {
            String fromNickname = request.getSession().getAttribute("nickname").toString();
            if (chatHistory.getFromUserId() != request.getSession().getAttribute("userId")) {
                fromNickname = userInfoService.getNicknameById(chatHistory.getFromUserId());
            }
            String toNickname = "所有人";
            if (chatHistory.getToUserId() != 0) {
                toNickname = userInfoService.getNicknameById(chatHistory.getToUserId());
            }
            HistoryMessageDTO historyMessageDTO = new HistoryMessageDTO(fromNickname,
                    toNickname,
                    chatHistory);
            historyMessageDTOList.add(historyMessageDTO);
        }
        return historyMessageDTOList;
    }
}
